package com.tuanzi.loan.web.bean.statistics.imei;

import com.tuanzi.loan.business.entity.statistics.ImeiMatchRecord;
import com.tuanzi.loan.business.entity.statistics.ImeiRecord;
import com.tuanzi.loan.business.service.statistics.ImeiStatService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.statistics.imei.ImeiStatRequest;
import com.tuanzi.loan.vo.response.statistics.imei.ImeiStatResponse;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import com.tuanzi.loan.web.lazy.statistics.imei.ImeiStatLazyDataModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.regex.Pattern;

@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
@Slf4j
public class ImeiStatListBean extends JSFListingBean<ImeiStatRequest, ImeiStatResponse> {

    @Autowired
    private ImeiStatService service;
    private static String pattern = "^[A-Za-z0-9]+$";

    private ImeiRecord imeiImportRecord = new ImeiRecord();
    private ImeiRecord imeiExportRecord = new ImeiRecord();
    ArrayList<String> imeiNumbers = new ArrayList<>();

    @PostConstruct
    private void init() {
        initLazyDataModel();
    }

    private void initLazyDataModel() {
        $ = new ImeiStatRequest();
        lazyDataModel = new ImeiStatLazyDataModel($);
    }

    public void onReset() {
        initLazyDataModel();
    }

    // 导入表格
    public void handleImportExcel(FileUploadEvent event) {
        InputStream inputstream = null;
        try {
            UploadedFile file = event.getFile();
            if (file == null || file.getInputstream() == null) {
                addErrorMessage("文件为空");
                return;
            }
            inputstream = file.getInputstream();
            extractImeiNumbers(inputstream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputstream != null) {
                try {
                    inputstream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void extractImeiNumbers(InputStream in) throws Exception {
        imeiNumbers.clear();
        Workbook workbook = WorkbookFactory.create(in);
        Sheet sheet = workbook.getSheetAt(0);
        int rowCount = sheet.getPhysicalNumberOfRows();
        for (int i = 0; i < rowCount; i++) {
            Row row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            Cell cell = row.getCell(0);
            if (cell == null) {
                continue;
            }
            if (cell.getCellType() == Cell.CELL_TYPE_STRING && Pattern.matches(pattern, cell.getStringCellValue())) {
                imeiNumbers.add(cell.getStringCellValue());
            }
        }
    }

    // 导入查询数据
    public void onImport() {
        try {
            if (imeiImportRecord.getCreateDate() == null || imeiImportRecord.getChannelCode() == null || imeiImportRecord.getPrdId() == null) {
                addErrorMessage("请填写所有表单项");
            } else if (imeiNumbers.isEmpty()) {
                addErrorMessage("无数据可导入");
            } else {
                imeiImportRecord.setImeiNumbers(imeiNumbers);
                service.importRecord(imeiImportRecord);
                addSuccessfullyMessage();
            }
        } catch (Exception e) {
            addErrorMessage("导入失败,请联系管理员");
            log.error("导入失败", e);
        } finally {
            execute("PF('doing').hide()");
            execute("PF('importDialog').hide()");
            update("imei-stat:statisticRecordDataTable");
            update("imei-stat:import-dialog");
            imeiImportRecord.getImeiNumbers().clear();
            imeiImportRecord.setCreateDate(null);
            imeiImportRecord.setChannelCode(null);
            imeiImportRecord.setPrdId(null);
            imeiNumbers.clear();
        }
    }

    public void onExport() {
        try {
            if (imeiExportRecord.getCreateDate() == null || imeiExportRecord.getChannelCode() == null || imeiExportRecord.getPrdId() == null) {
                addErrorMessage("请填写所有表单项");
            } else if (imeiNumbers.isEmpty()) {
                addErrorMessage("上传表格没有数据");
            } else {
                imeiExportRecord.setImeiNumbers(imeiNumbers);
                exportExcel(imeiExportRecord);
                addSuccessfullyMessage();
            }
        } catch (Exception e) {
            addErrorMessage("导出失败,请联系管理员");
            log.error("导出失败", e);
        } finally {
            execute("PF('doing').hide()");
            execute("PF('exportDialog').hide()");
            update("imei-stat:statisticRecordDataTable");
            update("imei-stat:export-dialog");
            imeiExportRecord.setCreateDate(null);
            imeiExportRecord.setChannelCode(null);
            imeiExportRecord.setPrdId(null);
            imeiNumbers.clear();
        }
    }

    public void exportExcel(ImeiRecord imeiExportRecord) throws IOException {
        ImeiMatchRecord imeiMatchRecord = service.exportRecord(imeiExportRecord);

        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("导出结果");
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);

        HSSFRow headerRow = sheet.createRow(0);
        HSSFCell headerCell = headerRow.createCell(0);
        headerCell.setCellValue("登录");
        headerCell.setCellStyle(cellStyle);
        headerCell = headerRow.createCell(1);
        headerCell.setCellValue("注册");
        headerCell.setCellStyle(cellStyle);

        int rows = imeiMatchRecord.getLoginList().size();
        for (int i = 1; i <= rows; i++) {
            sheet.createRow(i);
        }

        for (int i = 0; i < imeiMatchRecord.getLoginList().size(); i++) {
            HSSFRow row = sheet.getRow(i + 1);
            HSSFCell cell = row.createCell(0);
            cell.setCellValue(imeiMatchRecord.getLoginList().get(i));
            cell.setCellStyle(cellStyle);
        }

        for (int i = 0; i < imeiMatchRecord.getRegisterList().size(); i++) {
            HSSFRow row = sheet.getRow(i + 1);
            HSSFCell cell = row.createCell(1);
            cell.setCellValue(imeiMatchRecord.getRegisterList().get(i));
            cell.setCellStyle(cellStyle);
        }

        sheet.autoSizeColumn(0, true);
        sheet.autoSizeColumn(1, true);

        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();
        externalContext.setResponseContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        externalContext.setResponseHeader("Content-Disposition", "attachment; filename=export.xls");
        wb.write(externalContext.getResponseOutputStream());
        facesContext.responseComplete();
    }

    public void onDelete(Long id) {
        service.deleteById(id);
    }
}
